/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.monitor.profile.data;

import com.hyts.monitor.profile.config.ProfilerConfig;
import com.hyts.monitor.profile.context.ProfilerContext;

import java.util.concurrent.TimeUnit;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.monitor.profile.data
 * @author:LiBo/Alex
 * @create-date:2019-08-08 11:17
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description: methodCache 方法缓存信息数据对象
 */
public class MethodCache {


    private static final int DEFAULT_BATCH_NUM = 50;

    /**
     * 创建generate编号id method编号
     * @return
     */
    public static int generateId() throws InterruptedException {
        //校验是否达到最高值
        if(ProfilerConfig.AttributeConfig.DEFAULT_METHOD_CACHE_SIZE == ProfilerContext.getCacheRelationCache().size()){
            TimeUnit.SECONDS.sleep(5);
            //TODO 待完成相关的操作处理
        }
        ProfilerContext.getCacheRelationCache().add(new MethodData());
        return ProfilerContext.getCacheRelationCache().size() - 1;
    }

    /**
     * 更新方法的行号以及相关信息
     */
    public static void updateLineNum(int id,int lineNum){
        //校验id和行号是否符合校验规则
        MethodData methodData = ProfilerContext.getCacheRelationCache().get(id);
        if(methodData != null){
            methodData.setMethodLineNumber(lineNum);
        }
    }

    /**
     * 更新方法名称以及相关信息
     * @param id
     * @param fileName
     * @param className
     * @param methodName
     */
    public static void updateMethodName(int id,String fileName,String className,String methodName){
        MethodData methodData = ProfilerContext.getCacheRelationCache().get(id);
        if(methodData != null){
            methodData.setFileName(fileName);
            methodData.setClassName(className);
            methodData.setMethodName(methodName);
        }
    }

    /**
     * 操作flush刷新相关的所有目前环境内存中记载的数据采集的对象
     */
    public static CollectData collectCurrentMethdData(int batchNum){
        if (batchNum <= 0 ) {
            batchNum = DEFAULT_BATCH_NUM;
        }
        return CollectData.builder().
                instrumentClassNum(ProfilerContext.getCurrentSystemMonitorClassNum().get()).
                instrumentMethodNum(ProfilerContext.getCurrentSystemMonitorMethodNum().get()).
                methodDatas(ProfilerContext.getCacheRelationCache()).build();
    }
}
